package com.example.test02.util;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpService {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();
    private static final String BASE_URL = "http://localhost:8090/api";

    /**
     * 发送GET请求
     *
     * @param url 请求的URL
     * @param params 请求参数
     * @param callback 请求回调
     */
    public static void get(String url, Map<String, String> params, Callback callback) {
        Request.Builder requestBuilder = new Request.Builder()
                .url(buildUrl(url, params))
                .get();
        Request request = requestBuilder.build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 发送POST请求
     *
     * @param url 请求的URL
     * @param params 请求参数
     * @param callback 请求回调
     */
    public static void post(String url, Map<String, String> params, Callback callback) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            formBuilder.add(entry.getKey(), entry.getValue());
        }
        Request.Builder requestBuilder = new Request.Builder()
                .url(BASE_URL+url)
                .post(formBuilder.build());
        Request request = requestBuilder.build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 构建URL
     *
     * @param relativeUrl 基础URL
     * @param params 参数
     * @return 完整的URL
     */
    private static String buildUrl(String relativeUrl, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(BASE_URL);
        if (relativeUrl != null && !relativeUrl.isEmpty()) {
            sb.append(relativeUrl);
        }
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            boolean isFirst = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!isFirst) {
                    sb.append("&");
                } else {
                    isFirst = false;
                }
                if (entry.getKey() != null && entry.getValue() != null) {
                    sb.append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        return sb.toString();
    }
}


